import React, { useState } from 'react';
import axios from 'axios';


const Register = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);

  const handleSubmit = async (event) => {
    // 阻止表单提交的默认行为
    event.preventDefault();
    try {
      const response = await axios.post('http://localhost:3001/register', {
        username,
        password,
      });
      if (response.status === 201) {
        alert('User registered successfully!');
        window.location.href = '/login'; // 跳转到登录页面
      } else {
        setError(response.data.error);
      }
    } catch (error) {
      setError(error.message);
    }
  };

  return (
    <div>
      <h1>Register</h1>
      <form onSubmit={handleSubmit}>
        <label>
          Username:
          <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
        </label>
        <br />
        <label>
          Password:
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
        </label>
        <br />
        {error && <div style={{ color: 'red' }}>{error}</div>}
        <button type="submit">Register</button>
      </form>
    </div>
  );
};

export default Register;